<!--
 * @description: 仿真控制推演界面
 * @fileName: index.vue
 * @author: ssr
 * @date: 2022-08-16 11:16:49
 * @version: V1.0.0
!-->
<template>
  <div class="sub-container2">
    <SimHeader />
    <div class="sub-main">
      <CesiumMap v-model:custom-viewer="state.customViewer" />
      <DeductControl v-show="panelStore.controlPanelShow" @play="startPlayback" @pause="pausePlayback"
        @restart="restartSimulation" @speedChange="adjustPlaySpeed" @perspectiveChange="handlePerspectiveChange" />
      <DeductTime />
      <EntityList :class="panelStore.entityPanelShow ? 'expand' : 'collapse'" />
      <EntityLog :class="panelStore.logPanelShow ? 'expand' : 'collapse'" />
      <SystemInfo />
      <div class="step">
        <!-- 顶部：播放按钮 + 进度条 + 百分比 -->
        <div class="step-top">
          <!-- 左侧六边形播放键（把"左侧按钮"换掉） -->
          <div class="hex-play" @click="togglePlayState">
            <SvgIcon v-if="!state.isPlaying" name="bianzu-copy" class="ctrl-icon" />
            <SvgIcon v-else name="zanting" class="ctrl-icon" />
          </div>

          <!-- 原 el-progress -->
          <el-progress class="progress" :percentage="state.progressPercentage" :stroke-width="15" striped striped-flow
            :duration="30" :show-text="false" />
          <!-- 右侧百分比显示 -->
          <div class="percent">{{ state.progressPercentage }}</div>
        </div>

        <!-- 底部 3 个控制键：上一 / 停 / 下一 -->
        <div class="step-bottom">
          <el-tooltip content="快退" placement="top">
            <SvgIcon name="fast" class="ctrl-icon" @click="previousStep" />

          </el-tooltip>
          <el-tooltip content="重放" placement="top">
            <SvgIcon name="ic24-play-circle" class="ctrl-icon" @click="togglePlay" />

          </el-tooltip>
          <el-tooltip content="快进" placement="top">
            <SvgIcon name="fast" class="ctrl-icon" @click="nextStep" />
          </el-tooltip>
        </div>
      </div>

    </div>
  </div>
</template>
<script lang="ts" setup>
import {
  watch,
  reactive,
  toRefs,
  onMounted,
  onBeforeUnmount,
  defineOptions,
  onActivated,
  nextTick,
  computed
} from "vue";
import { createRoutesManager } from "@@/utils/RoutesManager";
import * as Cesium from "cesium";
import {
  CesiumMap,
  DeductControl,
  DeductTime,
  EntityList,
  EntityLog,
  SystemInfo,
} from "./components";
import SimHeader from "./components/header.vue";
import { getTaskSituationApi } from "@/common/apis/train";
import { useRoute } from "vue-router";
import {
  simulationState,
  simulPanelState,
  cesiumState,
  appState,
} from "@/pinia/stores/index";
import { customStomp } from "@@/utils/CustomStomp.ts";
import { EntityGroupId, ControlMessageType } from "@@/enums/observation.ts";
import { createDomainManager } from "@@/utils/DomainManager";
import { Cartesian3 } from "cesium";
// 命名，方便keepAlive识别
defineOptions({
  name: "situation", // 这里改成自己的组件名
})
// 定义类型
interface CustomViewer {
  animationManager?: {
    getAnimationGroup: (id: string) => {
      datasource: {
        show: boolean;
        entities: {
          getById: (id: string) => any;
        }
      }
    }
  };
  scene?: any;
}

interface ISideStep {
  game_id?: string;
  simul_time?: number;
  obj_list?: any[];
}

// 定义props
interface Props {
  roundNumber: string
  taskModeMap: string
}
const props = defineProps<Props>()
const route = useRoute();
// 使用store
const store = cesiumState();
const simulStore = simulationState();
const panelStore = simulPanelState();

// 定义响应式状态
let rmqTimer: NodeJS.Timeout | undefined;
const state = reactive({
  customViewer: null as CustomViewer | null,
  progressPercentage: "00:00:00" as string,
  currentStepIndex: 0,
  totalSteps: 100, // 假设总步骤数为100，可根据后端数据调整
  totalTime: 0, // 时长
  isPlaying: false,
  playSpeed: 1, // 播放速度倍率
});

// 计算播放图标
const playIcon = computed(() => state.isPlaying ? "video-pause" : "video-start");

// 切换播放状态
const togglePlayState = () => {
  state.isPlaying = !state.isPlaying;
  if (state.isPlaying) {
    startPlayback();
  } else {
    pausePlayback();
  }
};

// 切换播放/暂停
const togglePlay = () => {
  restartSimulation()
};

// 开始播放
const startPlayback = () => {
  // 防止多次调用
  if (rmqTimer) {
    clearInterval(rmqTimer);
  }
  // 重置位置逻辑
  if (state.currentStepIndex >= state.totalSteps - 1) {
    state.currentStepIndex = 0;
    updateProgress();
    applyStepData(state.currentStepIndex);
  }

  state.isPlaying = true;
  simulStore.setIsPause(false);

  rmqTimer = setInterval(() => {
    if (state.currentStepIndex < state.totalSteps - 1) {
      // 获取当前步骤的仿真时间
      const currentStep = simulStore.steps[state.currentStepIndex];
      if (currentStep && currentStep.simul_time) {
        // 找到下一个时间点的步骤
        const nextIndex = simulStore.steps.findIndex((step, index) =>
          index > state.currentStepIndex && step.simul_time > currentStep.simul_time
        );

        if (nextIndex !== -1) {
          state.currentStepIndex = nextIndex;
          updateProgress();
          applyStepData(state.currentStepIndex);
          // 更新显示的时间为当前时间/总时间
          const timeStr = new Date(currentStep.simul_time * 1000).toISOString().substr(11, 8);
          const totalTimeStr = new Date(state.totalTime * 1000).toISOString().substr(11, 8);
          state.progressPercentage = `${totalTimeStr}`;
          updateSimulationTime(currentStep.simul_time);
        } else {
          // 如果没有找到下一个时间点，说明已经到达最后
          pausePlayback();
        }
      }
    } else {
      pausePlayback();
    }
  }, 1000 / state.playSpeed);
};

// 暂停播放
const pausePlayback = () => {
  if (rmqTimer) {
    clearInterval(rmqTimer);
    rmqTimer = undefined;
  }
  simulStore.setIsPause(true);
  state.isPlaying = false;

  // 停止更新时间和进度条
  const currentStep = simulStore.steps[state.currentStepIndex];
  if (currentStep && currentStep.simul_time) {
    // 更新显示的时间为当前时间
    const timeStr = new Date(currentStep.simul_time * 1000).toISOString().substr(11, 8);
    state.progressPercentage = timeStr;
    updateSimulationTime(currentStep.simul_time);
  }
};

// 下一步
const nextStep = () => {
  if (state.currentStepIndex < state.totalSteps - 1) {
    // 获取当前步骤的仿真时间
    const currentStep = simulStore.steps[state.currentStepIndex];
    if (currentStep && currentStep.simul_time) {
      // 找到下一个时间点的步骤
      const nextIndex = simulStore.steps.findIndex((step, index) =>
        index > state.currentStepIndex && step.simul_time > currentStep.simul_time
      );

      if (nextIndex !== -1) {
        state.currentStepIndex = nextIndex;
        updateProgress();
        applyStepData(state.currentStepIndex);
        // 更新显示的时间为当前时间/总时间
        const timeStr = new Date(currentStep.simul_time * 1000).toISOString().substr(11, 8);
        const totalTimeStr = new Date(state.totalTime * 1000).toISOString().substr(11, 8);
        state.progressPercentage = `${totalTimeStr}`;
        updateSimulationTime(currentStep.simul_time);
      }
    }
  }
};

// 上一步
const previousStep = () => {
  if (state.currentStepIndex > 0) {
    // 获取当前步骤的仿真时间
    const currentStep = simulStore.steps[state.currentStepIndex];
    if (currentStep && currentStep.simul_time) {
      // 找到上一个时间点的步骤
      const prevIndex = simulStore.steps.findIndex((step, index) =>
        index < state.currentStepIndex && step.simul_time < currentStep.simul_time
      );

      if (prevIndex !== -1) {
        state.currentStepIndex = prevIndex;
        updateProgress();
        applyStepData(state.currentStepIndex);
        // 只显示当前时间
        const timeStr = new Date(currentStep.simul_time * 1000).toISOString().substr(11, 8);
        const totalTimeStr = new Date(state.totalTime * 1000).toISOString().substr(11, 8);
        state.progressPercentage = `${totalTimeStr}`;
        updateSimulationTime(currentStep.simul_time);
      }
    }
  }
};

// 更新进度
const updateProgress = () => {
  const currentStep = simulStore.steps[state.currentStepIndex];
  if (currentStep && currentStep.simul_time && state.totalTime) {
    // 计算当前进度百分比
    const progress = (currentStep.simul_time / state.totalTime) * 100;
    // 更新进度条
    const progressBar = document.querySelector('.el-progress-bar__inner') as HTMLElement;
    if (progressBar) {
      progressBar.style.width = `${progress}%`;
    }
  }
};

// 应用步骤数据
const applyStepData = async (stepIndex: number) => {
  if (stepIndex < 0 || stepIndex >= simulStore.steps.length) {
    return;
  }

  // 获取当前步骤数据
  let stepData = simulStore.applyStepData(stepIndex);

  if (!stepData) {
    return;
  }

  // 使用处理观察数据的新方法
  await simulStore.processObservationData(stepIndex);

  // 处理实体数据
  processEntityData(stepData);

  // 更新3D视图
  updateVisualization(stepData);

  //
};

// 获取当前视角的步骤数据
const getStepDataForCurrentPerspective = (stepIndex: number) => {

  let stepData;
  if (simulStore.currentPerspective === 'red') {
    if (simulStore.redSteps && simulStore.redSteps.length > stepIndex) {
      stepData = simulStore.redSteps[stepIndex];
    }
  } else if (simulStore.currentPerspective === 'blue') {
    if (simulStore.blueSteps && simulStore.blueSteps.length > stepIndex) {
      stepData = simulStore.blueSteps[stepIndex];
    }
  } else {
    if (simulStore.steps && simulStore.steps.length > stepIndex) {
      stepData = simulStore.steps[stepIndex];
    }
  }

  if (!stepData) {
    // 如果没有对应视角的数据，回退到全局数据
    stepData = simulStore.steps[stepIndex];
  }

  return stepData;
};

// 更新仿真时间
const updateSimulationTime = (simulTime: any) => {
  simulStore.setSimulTime(simulTime);
};

// 处理实体数据
const processEntityData = (stepData) => {
  if (!stepData.obj_list) return;
  // 更新实体位置
  if (state.customViewer) {
    updateEntityPositions(state.customViewer, stepData);
  }

  // 更新路径显示 - 修改条件确保始终尝试更新轨迹
  if (simulStore.routesManager) {
    // 确保路径显示标志为真
    if (!simulStore.isShowPath) {
      simulStore.isShowPath = true;
    }
    updateRoutes(simulStore.routesManager, stepData);
  } else {
  }

  // 更新日志信息
  updateLogs(stepData);
};

// 更新可视化
const updateVisualization = (stepData) => {
  // 请求重新渲染
  if (state.customViewer?.scene) {
    try {
      state.customViewer.scene.requestRender();
    } catch (e) {
    }
  }
};

// 更新实体位置
const updateEntityPositions = (customViewer: CustomViewer, step: ISideStep) => {
  if (!step.obj_list) return;

  // 获取动画管理器的实体组
  const groupAll = customViewer.animationManager?.getAnimationGroup(EntityGroupId.all),
    groupRed = customViewer.animationManager?.getAnimationGroup(EntityGroupId.red),
    groupBlue = customViewer.animationManager?.getAnimationGroup(EntityGroupId.blue);

  // 遍历实体列表，更新位置
  step.obj_list && step.obj_list.forEach((entity: any) => {
    // 对于1.json数据需要转换字段
    const entity_id = entity.m_id?.toString() || entity.entity_id;
    const alliance = entity.m_Side === 1 ? "Red" : (entity.alliance || "Blue");
    let position;

    // 检查位置数据的格式并处理
    if (entity.m_Position) {
      // 从1.json数据中提取位置
      position = `${entity.m_Position.longitude},${entity.m_Position.latitude},${entity.m_Position.height || 0}`;
    } else {
      position = entity.position;
    }

    if (position) {
      const pos = position.split(","); // 经度,纬度,高度
      if (pos && pos.length === 3) {
        // 使用Cesium的Cartesian3.fromDegrees将经纬度转换为笛卡尔坐标
        const cartesian = Cesium.Cartesian3.fromDegrees(
          Number(pos[0]),
          Number(pos[1]),
          Number(pos[2])
        );

        // 根据alliance更新对应阵营的实体
        let targetEntity;
        if (alliance === "Blue") {
          targetEntity = groupBlue?.datasource.entities.getById(entity_id);
        } else {
          targetEntity = groupRed?.datasource.entities.getById(entity_id);
        }

        // 如果实体不存在，则创建
        if (!targetEntity) {
          // 创建实体
          const entityGroup = alliance === "Blue" ? groupBlue : groupRed;
          if (entityGroup) {
            entityGroup.datasource.entities.add({
              id: entity_id,
              name: entity.m_EntityName || entity.entity_name,
              position: cartesian,
              point: {
                pixelSize: 10,
                color: alliance === "Blue" ? Cesium.Color.BLUE : Cesium.Color.RED
              }
            });
          }
        } else {
          // 更新实体位置
          if (targetEntity.position) {
            targetEntity.position.setValue(cartesian);
          }
        }
      }
    }
  });
};

// 更新轨迹
const updateRoutes = (routesManager: any, step: ISideStep) => {
  if (!step.obj_list) return;
  if (!routesManager) return;
  if (!routesManager.entityRoutes) routesManager.entityRoutes = {};

  // 确保entityRoutes中没有对象值
  cleanAllEntityRoutes(routesManager);

  step.obj_list && step.obj_list.forEach((entity: any) => {
    const entity_id = entity.m_id?.toString() || entity.entity_id;
    let position;

    // 检查位置数据的格式并处理
    if (entity.m_Position) {
      position = `${entity.m_Position.longitude},${entity.m_Position.latitude},${entity.m_Position.height || 0}`;
    } else {
      position = entity.position;
    }

    if (position) {
      const pos = position.split(","); // 经度,纬度,高度
      if (pos && pos.length === 3) {
        try {
          // 确保所有坐标都是数字
          const longitude = Number(pos[0]);
          const latitude = Number(pos[1]);
          const height = Number(pos[2]);

          // 验证转换是否成功且数值有效
          if (isNaN(longitude) || isNaN(latitude) || isNaN(height)) {
            console.warn("坐标转换失败，跳过该点:", position);
            return;
          }

          const cartesian = Cesium.Cartesian3.fromDegrees(longitude, latitude, height);

          // 确保路径数组存在且仅包含数字
          if (!routesManager.entityRoutes[entity_id]) {
            routesManager.entityRoutes[entity_id] = [];
          } else {
            // 如果已存在，确保数组中只有数字
            const cleanedArray = [];
            for (let i = 0; i < routesManager.entityRoutes[entity_id].length; i++) {
              if (typeof routesManager.entityRoutes[entity_id][i] === 'number') {
                cleanedArray.push(routesManager.entityRoutes[entity_id][i]);
              }
            }
            routesManager.entityRoutes[entity_id] = cleanedArray;
          }

          // 直接添加经纬度(一定是数字类型)
          routesManager.entityRoutes[entity_id].push(longitude, latitude);
        } catch (error) {
          console.error("处理实体位置错误:", error, position);
        }
      }
    }
  });

  // 清理和刷新路径
  refreshAllEntityRoutes(routesManager);
};

// 清理所有路径数据，确保只有数字
const cleanAllEntityRoutes = (routesManager: any) => {
  if (!routesManager || !routesManager.entityRoutes) return;

  const cleanedRoutes = {};

  for (const entityId in routesManager.entityRoutes) {
    const routes = routesManager.entityRoutes[entityId];
    if (!Array.isArray(routes)) {
      console.warn(`实体 ${entityId} 的路径不是数组类型，重置为空数组`);
      cleanedRoutes[entityId] = [];
      continue;
    }

    // 过滤出所有数字类型的值
    const validNumbers = [];
    for (let i = 0; i < routes.length; i++) {
      if (typeof routes[i] === 'number' && !isNaN(routes[i])) {
        validNumbers.push(routes[i]);
      } else if (typeof routes[i] === 'object' && routes[i] !== null) {
        // 尝试从对象转换为经纬度
        try {
          // 尝试从对象创建Cartesian3
          const cartesian = new Cesium.Cartesian3(
            routes[i].x || 0,
            routes[i].y || 0,
            routes[i].z || 0
          );
          // 转换为经纬度
          const cartographic = Cesium.Cartographic.fromCartesian(cartesian);
          const longitude = Cesium.Math.toDegrees(cartographic.longitude);
          const latitude = Cesium.Math.toDegrees(cartographic.latitude);

          // 验证转换是否成功且有效
          if (!isNaN(longitude) && !isNaN(latitude)) {
            validNumbers.push(longitude, latitude);
          }
        } catch (e) {
          // 忽略无法转换的对象
          console.warn("无法转换的路径点对象", routes[i]);
        }
      } else if (typeof routes[i] === 'string') {
        // 尝试将字符串转换为数字
        const num = Number(routes[i]);
        if (!isNaN(num)) {
          validNumbers.push(num);
        }
      }
    }

    // 确保长度是偶数(有效的经纬度对)
    if (validNumbers.length % 2 !== 0) {
      validNumbers.pop();
    }

    cleanedRoutes[entityId] = validNumbers;
  }

  // 用清理后的数据替换原数据
  routesManager.entityRoutes = cleanedRoutes;
};

// 刷新所有路径
const refreshAllEntityRoutes = (routesManager: any) => {
  if (!routesManager || !routesManager.datasource) return;

  try {
    // 清除现有实体
    routesManager.datasource.entities.removeAll();

    // 确保先清理所有路径数据
    cleanAllEntityRoutes(routesManager);

    // 绘制所有有效路径
    for (const entityId in routesManager.entityRoutes) {
      const routes = routesManager.entityRoutes[entityId];

      // 至少需要2个点(4个坐标值)
      if (routes.length >= 4) {
        try {
          // 确保所有值都是数字
          for (let i = 0; i < routes.length; i++) {
            if (typeof routes[i] !== 'number' || isNaN(routes[i])) {
              console.error(`路径点 ${i} 不是有效数字:`, routes[i]);
              return; // 如果任何一个不是数字，跳出当前路径
            }
          }

          // 创建实体路径
          const entity = new Cesium.Entity({
            id: entityId,
            polyline: {
              positions: Cesium.Cartesian3.fromDegreesArray(routes),
              width: 1,
              material: new Cesium.PolylineDashMaterialProperty({
                color: Cesium.Color.fromCssColorString("rgba(53, 181, 255, 1)")
              })
            }
          });

          routesManager.datasource.entities.add(entity);
        } catch (error) {
          console.error("创建路径实体失败:", error, routes);
          // 如果创建失败，移除可能出问题的路径
          delete routesManager.entityRoutes[entityId];
        }
      }
    }
  } catch (error) {
    console.error("刷新路径失败:", error);
  }
};

// 更新日志
const updateLogs = (step: ISideStep) => {
  if (!step.obj_list) return;

  const redLogList: any[] = [];
  const blueLogList: any[] = [];

  // 自定义日志转换函数
  const entity2Log = (entity: any, log: any) => {
    return {
      id: entity.m_id?.toString() || entity.entity_id,
      time: log.time || new Date().toISOString(),
      content: log.content || "状态更新",
      type: log.type || "信息"
    };
  };

  // 遍历实体，提取日志
  step.obj_list && step.obj_list.forEach((entity: any) => {
    const entity_id = entity.m_id?.toString() || entity.entity_id;
    const alliance = entity.m_Side === 1 ? "Red" : (entity.alliance || "Blue");
    const logs = entity.logs || [];

    // 为每个实体创建一个状态更新日志
    const statusLog = {
      time: new Date().toISOString(),
      content: `${entity.m_EntityName || entity.entity_name} 位置更新`,
      type: "状态"
    };

    if (alliance === "Blue") {
      blueLogList.push(entity2Log(entity, statusLog));
    } else {
      redLogList.push(entity2Log(entity, statusLog));
    }

    if (logs.length > 0) {
      logs.forEach((log: any) => {
        if (alliance === "Blue") {
          blueLogList.push(entity2Log(entity, log));
        } else {
          redLogList.push(entity2Log(entity, log));
        }
      });
    }
  });

  // 更新日志到store
  if (redLogList.length > 0) {
    simulStore.entityLog.red = [
      ...simulStore.entityLog.red,
      ...redLogList
    ];
  }

  if (blueLogList.length > 0) {
    simulStore.entityLog.blue = [
      ...simulStore.entityLog.blue,
      ...blueLogList
    ];
  }
};

// 组件挂载成功后
onMounted(async () => {
  // 加载初始数据
  await loadDeductionData();

  // 确保轨迹显示开启
  simulStore.isShowPath = true;

  // 等待视图器创建完成
  nextTick(async () => {
    if (state.customViewer) {
      // 初始化轨迹管理器
      if (!simulStore.routesManager) {
        const baseManager = createRoutesManager();

        // 添加缺失的方法，防止坐标数量错误
        const extendedManager = baseManager as any;

        extendedManager.addPathPoint = function (entityId: string, cartesian: Cesium.Cartesian3): void {
          if (!this.entityRoutes) this.entityRoutes = {};
          if (!this.entityRoutes[entityId]) {
            this.entityRoutes[entityId] = [];
          }

          // 确保添加的是经纬度坐标（转换为经纬度数组）
          const cartographic = Cesium.Cartographic.fromCartesian(cartesian);
          const longitude = Cesium.Math.toDegrees(cartographic.longitude);
          const latitude = Cesium.Math.toDegrees(cartographic.latitude);

          // 验证转换是否成功
          if (isNaN(longitude) || isNaN(latitude)) {
            return;
          }

          // 添加经纬度坐标点（成对添加，确保坐标是2的倍数）
          this.entityRoutes[entityId].push(longitude, latitude);

          // 如果路径已经有更新，刷新显示
          if (this.entityRoutes[entityId].length >= 4) {
            // 验证所有坐标是数字
            for (let i = 0; i < this.entityRoutes[entityId].length; i++) {
              if (typeof this.entityRoutes[entityId][i] !== 'number' || isNaN(this.entityRoutes[entityId][i])) {
                return;
              }
            }
            this.refreshRoutes();
          }
        };

        extendedManager.addPoint = extendedManager.addPathPoint;
        extendedManager.addPath = extendedManager.addPathPoint;

        // 添加刷新方法
        extendedManager.refreshRoutes = function (): void {
          if (!this.datasource) return;

          // 确保所有轨迹数据都是数字
          cleanAllEntityRoutes(this);
          refreshAllEntityRoutes(this);
        };
        simulStore.routesManager = extendedManager;
      }

      // 使用store中的方法初始化实体列表
      simulStore.initializeEntityList(simulStore.steps);

      // 应用第一步数据
      await applyStepData(0);
    }
  });
});

watch(() => props.roundNumber, async (newVal) => {
  if (newVal) {
    // 加载初始数据
    await loadDeductionData();

    // 确保轨迹显示开启
    simulStore.isShowPath = true;

    // 等待视图器创建完成
    nextTick(async () => {
      if (state.customViewer) {
        // 初始化轨迹管理器
        if (!simulStore.routesManager) {
          const baseManager = createRoutesManager();

          // 添加缺失的方法，防止坐标数量错误
          const extendedManager = baseManager as any;

          extendedManager.addPathPoint = function (entityId: string, cartesian: Cesium.Cartesian3): void {
            if (!this.entityRoutes) this.entityRoutes = {};
            if (!this.entityRoutes[entityId]) {
              this.entityRoutes[entityId] = [];
            }

            // 确保添加的是经纬度坐标
            const cartographic = Cesium.Cartographic.fromCartesian(cartesian);
            const longitude = Cesium.Math.toDegrees(cartographic.longitude);
            const latitude = Cesium.Math.toDegrees(cartographic.latitude);

            // 验证转换是否成功
            if (isNaN(longitude) || isNaN(latitude)) {
              return;
            }

            // 添加经纬度坐标点（成对添加）
            this.entityRoutes[entityId].push(longitude, latitude);

            // 如果路径已经有更新，刷新显示
            if (this.entityRoutes[entityId].length >= 4) {
              this.refreshRoutes();
            }
          };

          extendedManager.addPoint = extendedManager.addPathPoint;
          extendedManager.addPath = extendedManager.addPathPoint;

          // 添加刷新方法
          extendedManager.refreshRoutes = function (): void {
            if (!this.datasource) return;

            // 清理并刷新轨迹数据
            cleanAllEntityRoutes(this);
            refreshAllEntityRoutes(this);
          };

          simulStore.routesManager = extendedManager;
        }

        // 使用store中的方法初始化实体列表
        simulStore.initializeEntityList(simulStore.steps);

        // 应用第一步数据
        await applyStepData(0);
      }
    });
  }
});

// 组件激活时（从缓存中恢复）
onActivated(async () => {
  await loadDeductionData();
  // 确保轨迹显示开启
  simulStore.isShowPath = true;

  // 等待视图器创建完成
  nextTick(async () => {
    if (state.customViewer) {
      // 初始化轨迹管理器
      if (!simulStore.routesManager) {
        const baseManager = createRoutesManager();

        // 添加缺失的方法，防止坐标数量错误
        const extendedManager = baseManager as any;

        extendedManager.addPathPoint = function (entityId: string, cartesian: Cesium.Cartesian3): void {
          if (!this.entityRoutes) this.entityRoutes = {};
          if (!this.entityRoutes[entityId]) {
            this.entityRoutes[entityId] = [];
          }

          // 确保添加的是经纬度坐标
          const cartographic = Cesium.Cartographic.fromCartesian(cartesian);
          const longitude = Cesium.Math.toDegrees(cartographic.longitude);
          const latitude = Cesium.Math.toDegrees(cartographic.latitude);

          // 验证转换是否成功
          if (isNaN(longitude) || isNaN(latitude)) {
            return;
          }

          // 添加经纬度坐标点（成对添加）
          this.entityRoutes[entityId].push(longitude, latitude);

          // 如果路径已经有更新，刷新显示
          if (this.entityRoutes[entityId].length >= 4) {
            this.refreshRoutes();
          }
        };

        extendedManager.addPoint = extendedManager.addPathPoint;
        extendedManager.addPath = extendedManager.addPathPoint;

        // 添加刷新方法
        extendedManager.refreshRoutes = function (): void {
          if (!this.datasource) return;

          // 清理并刷新轨迹数据
          cleanAllEntityRoutes(this);
          refreshAllEntityRoutes(this);
        };

        simulStore.routesManager = extendedManager;
      }

      // 使用store中的方法初始化实体列表
      simulStore.initializeEntityList(simulStore.steps);

      // 应用第一步数据
      await applyStepData(0);
    }
  });
});

// 组件销毁
onBeforeUnmount(() => {
  rmqTimer && clearInterval(rmqTimer);
  if (simulStore.clientId) {
    try {
      customStomp.removeClient(simulStore.clientId);
      simulStore.setIsPause(true);
    } catch (error) {
      // 忽略错误
    }
  }
});

// 暴露给模板使用的变量和方法
defineExpose({
  panelStore,
  ...toRefs(state),
  playIcon,
  togglePlayState,
  togglePlay,
  nextStep,
  previousStep
});

// 重启仿真
const restartSimulation = async () => {
  // 清除定时器
  if (rmqTimer) {
    clearInterval(rmqTimer);
    rmqTimer = undefined;
  }

  // 重置状态
  state.currentStepIndex = 0;
  state.isPlaying = false;
  updateProgress();

  // 重新加载数据
  await loadDeductionData();

  // 应用第一步数据
  await applyStepData(0);

  // 关闭加载提示
  const app = appState();
  app.spinning = false;
  startPlayback();
};

// 调整播放速度
const adjustPlaySpeed = (speed) => {
  state.playSpeed = speed;

  // 如果正在播放，重启定时器使用新速度
  if (state.isPlaying) {
    pausePlayback();
    startPlayback();
  }
};

// 处理视角变化
const handlePerspectiveChange = async (perspective: string) => {
  // 更新store中的视角设置
  simulStore.currentPerspective = perspective;

  // 确保切换前清理所有路径数据
  if (simulStore.routesManager) {
    cleanAllEntityRoutes(simulStore.routesManager);
  }

  // 使用processObservationData处理当前步骤的数据
  await simulStore.processObservationData(state.currentStepIndex);

  // 重新应用当前步骤数据
  const stepData = simulStore.applyStepData(state.currentStepIndex);

  if (stepData) {
    // 处理实体数据并刷新路径
    processEntityData(stepData);

    // 确保切换后再次清理和刷新所有路径
    if (simulStore.routesManager) {
      refreshAllEntityRoutes(simulStore.routesManager);
    }
  }

  // 请求重新渲染
  if (state.customViewer?.scene) {
    try {
      state.customViewer.scene.requestRender();
    } catch (e) {
      console.error("视图渲染失败:", e);
    }
  }
};

// 加载推演数据
const loadDeductionData = async () => {
  try {
    if (!(route.query.id && props.taskModeMap && props.roundNumber)) return
    const response = await getTaskSituationApi(route.query.id as string, props.taskModeMap, props.roundNumber) as any;

    const data = response.data;
    // 使用我们添加的新方法加载数据
    const success = simulStore.loadLocalData(data);

    if (success) {
      // 设置总步骤数和初始状态
      state.totalSteps = simulStore.steps.length;
      state.currentStepIndex = 0;

      // 获取最后一步的时间作为总时长
      const lastStep = simulStore.steps[state.totalSteps - 1];
      if (lastStep && lastStep.simul_time) {
        state.totalTime = lastStep.simul_time;
        // 设置初始显示为 00:00:00 / 总时长
        const totalTimeStr = new Date(state.totalTime * 1000).toISOString().substr(11, 8);
        state.progressPercentage = `${totalTimeStr}`;
      }

      updateProgress();

      // 确保轨迹显示已开启
      simulStore.isShowPath = true;

      return true;
    } else {
      return false;
    }
  } catch (error) {
    return false;
  }
};

// 初始化实体列表 - 提前从所有步骤中收集实体信息
const initializeEntityList = (steps) => {
  // 收集所有实体信息
  const redEntities = new Map();
  const blueEntities = new Map();

  steps.forEach(step => {
    if (!step.obj_list) return;

    step.obj_list && step.obj_list.forEach(entity => {
      const entityId = entity.m_id?.toString() || entity.entity_id;
      const alliance = entity.m_Side === 1 ? "Red" : "Blue";
      const entityName = entity.m_EntityName || entity.entity_name || "未命名实体";

      if (alliance === "Red") {
        if (!redEntities.has(entityId)) {
          redEntities.set(entityId, {
            id: entityId,
            name: entityName,
            // 其他属性
          });
        }
      } else {
        if (!blueEntities.has(entityId)) {
          blueEntities.set(entityId, {
            id: entityId,
            name: entityName,
            // 其他属性
          });
        }
      }
    });
  });

  // 更新实体ID列表
  simulStore.entityIds = {
    red: Array.from(redEntities.keys()),
    blue: Array.from(blueEntities.keys())
  };

  // 更新实体信息列表
  simulStore.entityList = {
    red: Array.from(redEntities.values()),
    blue: Array.from(blueEntities.values())
  };
};

// 监听视图创建实体路径
watch(() => state.customViewer, (newViewer) => {
  if (newViewer) {
    // 创建实体轨迹
    const baseManager = createRoutesManager();

    // 添加缺失的方法，防止坐标数量错误
    const extendedManager = baseManager as any;

    extendedManager.addPathPoint = function (entityId: string, cartesian: Cesium.Cartesian3): void {
      if (!this.entityRoutes) this.entityRoutes = {};
      if (!this.entityRoutes[entityId]) {
        this.entityRoutes[entityId] = [];
      }

      // 确保添加的是经纬度坐标
      const cartographic = Cesium.Cartographic.fromCartesian(cartesian);
      const longitude = Cesium.Math.toDegrees(cartographic.longitude);
      const latitude = Cesium.Math.toDegrees(cartographic.latitude);

      // 验证转换是否成功
      if (isNaN(longitude) || isNaN(latitude)) {
        console.warn("坐标转换失败，跳过该点");
        return;
      }

      // 添加经纬度坐标点（成对添加）
      this.entityRoutes[entityId].push(longitude, latitude);

      // 如果路径已经有更新，刷新显示
      if (this.entityRoutes[entityId].length >= 4) {
        this.refreshRoutes();
      }
    };

    extendedManager.addPoint = extendedManager.addPathPoint;
    extendedManager.addPath = extendedManager.addPathPoint;

    // 添加刷新方法
    extendedManager.refreshRoutes = function (): void {
      if (!this.datasource) return;

      // 清理并刷新轨迹数据
      cleanAllEntityRoutes(this);
      refreshAllEntityRoutes(this);
    };

    simulStore.routesManager = extendedManager;
    simulStore.domainManager = createDomainManager();

    // 确保轨迹显示开启
    simulStore.isShowPath = true;

    // 初始化数据
    if (simulStore.steps?.length) {
      initializeEntityList(simulStore.steps);
    }
  }
}, { immediate: true });
</script>
<style lang="less">
@import "@@/assets/styles/submodule2.less";

.sub-main {
  position: relative;
}

/* ====== 外层容器 ====== */
.step {
  position: absolute;
  left: 50%;
  bottom: 30px;
  transform: translateX(-50%);
  width: 96%;
  padding-right: 10px;
  height: 117px;
  display: flex;
  flex-direction: column;
  justify-content: space-evenly;
  border-radius: 4px;
  background: rgba(0, 0, 0, 0.45);
  backdrop-filter: blur(2px);
}

.step-top {
  display: flex;
  align-items: center;
  gap: 14px;
  padding: 0 8px;
}

/* 六边形播放按钮 */
.hex-play {
  width: 38px;
  height: 38px;
  cursor: pointer;
  clip-path: polygon(25% 5%, 75% 5%, 100% 50%, 75% 95%, 25% 95%, 0 50%);
  background: rgba(11, 89, 100, 0.25);
  border: 1px solid #32d1d1;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* el-progress 条：占满剩余宽度 */
.progress {
  flex: 1;
  --el-progress-text-color: transparent;
  /* 隐藏百分比文字 */
}

.progress .el-progress-bar__inner {
  background: #32d1d1 !important;
}

/* 右侧百分比 */
.percent {
  width: 52px;
  text-align: right;
  font-size: 16px;
  font-weight: 600;
  color: #32d1d1;
}

/* ====== 底部控制区 ====== */
.step-bottom {
  display: flex;
  justify-content: center;
  gap: 100px;
}

.ctrl-icon {
  font-size: 24px;
  color: #fff;
  cursor: pointer;
  transition: color 0.2s;
  cursor: pointer;

}

.ctrl-icon:hover {
  color: #32d1d1;
}
</style>
